package com.ljl.question4;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageHandler;

/**
 * @author 20664
 */
@Configuration
@EnableIntegration
public class HeatBeatHandler {
    @Bean
    public MessageProducerSupport mqttInbound() {
        String topics = "testHeartbeat";
        String broken = "tcp://broker.emqx.io:1883";
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(broken, "spring_consumer", topics);
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(0);
        return adapter;
    }

    @Bean
    public MessageHandler mqttOutbound() {
        String broken = "tcp://broker.emqx.io:1883";
        String topic = "heartbeatResponse";
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(broken, "spring_producer");
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(topic);
        return messageHandler;
    }

    @Bean
    public IntegrationFlow integrationFlow() {
        return IntegrationFlow.from(mqttInbound())
                .handle((p, h) -> {
                    System.out.println("Received message: " + p);
                    return "ok";
                })
                .handle(mqttOutbound())
                .get();
    }

}
